const {schoolInfo,sequelize,userInfo,userledger} = require('../dbConfig/index.js')
const {  getMenuPageList, } = require('../utils/menu.js')
// 新增院校
// 先增院校 再增用户信息  再增用户名 用事务
const addSchool = async (ctx,next)=>{
    const { school_name,school_city_name,school_phone,school_duty,school_duty_position,school_logo } = ctx.request.body
    //校验
    if(!(school_name&&school_city_name&&school_phone&&school_duty&&school_duty_position&&school_logo)){
        ctx.body = {
            code:1,
            data:null,
            msg:'请填写完整信息'
        }
        return
    }
    const transaction = await sequelize.transaction();
    const res = await schoolInfo.create({
        school_name,
        school_city_name,
        school_phone,
        school_duty,
        school_duty_position,
        school_logo,
        school_student_num:0,
        school_menu_ids:''
    },{  transaction });
const info = await userInfo.create({
    identity:1,
    user_name:school_duty,
    user_sex:'男',
    user_age:20,
    user_address:'未知',
    level_title:'未知',
    belong_to_school:res.school_id
},{  transaction });

    await userledger.create({
        user_phone:school_phone,
        user_password:'admin123',
        info_id:info.user_id

    },{  transaction });

    await transaction.commit();
       
    ctx.body = {
        code:200,
        data:null,
        msg:'添加成功,初始密码 admin123'
    }
}
const adduser = async (ctx,next)=>{
    const { identity,role_id,specialty,endSchool,teacher_phone,user_name,user_sex,user_age,user_address,level_title,belong_to_school } = ctx.request.body
    //校验
    if(!(identity&&role_id&&user_name&&user_sex&&user_age&&user_address&&level_title&&belong_to_school)){
        ctx.body = {
            code:1,
            data:null,
            msg:'请填写完整信息'
        }
        return
    }
    const transaction = await sequelize.transaction();
    const res = await userInfo.create({
        identity,
        role_id,
        specialty,
        endSchool,
        user_name,
        user_sex,
        user_age,
        user_address,
        level_title,
        belong_to_school
    },{  transaction });
    
    await userledger.create({
        user_phone:teacher_phone,
        user_password:'admin123',
        info_id:res.user_id
    },{ transaction })
    await transaction.commit();
       
    ctx.body = {
        code:200,
        data:null,
        msg:'添加成功,初始密码 admin123'
    }       
}
const getUserList = async (ctx,next)=>{
    try {
        const { school_id, identity, page = 1, size = 10 } = ctx.request.body;
        
        // 校验参数
        if (!school_id || !identity) {
            ctx.body = {
                code: 1,
                data: null,
                msg: '缺少必要参数'
            };
            return;
        }
        
        // 确保 page 和 size 是有效数字
        const parsedPage = parseInt(page);
        const parsedSize = parseInt(size);
        
        if (isNaN(parsedPage) || isNaN(parsedSize) || parsedPage < 1 || parsedSize < 1) {
            ctx.body = {
                code: 1,
                data: null,
                msg: '分页参数无效'
            };
            return;
        }
        
        // 查询总记录数
        const total = await userInfo.count({
            where: {
                identity,
                belong_to_school: school_id
            }
        });
        
        // 分页查询
        const res = await userInfo.findAll({
            where: {
                identity,
                belong_to_school: school_id
            },
            offset: (parsedPage - 1) * parsedSize,
            limit: parsedSize
        });
        
        ctx.body = {
            code: 200,
            data: {
                list: res,
                total,
                page: parsedPage,
                size: parsedSize
            },
            msg: '获取成功'
        };
    } catch (error) {
        console.error('获取用户列表失败:', error);
        ctx.body = {
            code: 500,
            data: null,
            msg: '服务器错误'
        };
    }
}
// 教师信息修改
const editTeacher = async (ctx,next)=>{
    const { identity,role_id,specialty,endSchool,user_name,user_sex,user_age,user_address,level_title,belong_to_school,user_id } = ctx.request.body
    //校验
    if(!(user_id&&identity&&role_id&&user_name&&user_sex&&user_age&&user_address&&level_title&&belong_to_school)){
        ctx.body = {
            code:1,
            data:null,
            msg:'请填写完整信息'
        }
        return
    }
    const res = await userInfo.update({
        identity,
        role_id,
        specialty,
        endSchool,
        user_name,
        user_sex,
        user_age,
        user_address,
        level_title,
        belong_to_school
    },{  where:{user_id}});
   
    ctx.body = {code:200,data:null,msg:'成功'}
}

// 获取院校列表
const getSchool = async (ctx,next)=>{
    if(ctx.state.user_id===0){
        const res = await schoolInfo.findAll()
        ctx.body = {
            code:200,
            data:res,
            msg:'获取成功'
        }
    }else{
        ctx.body = {
            code:1,
            data:null,
            msg:'权限不足'
        }
    }
}
// 设置院校菜单
const setSchoolMenu = async (ctx,next)=>{
    const {school_id,school_menu_ids} = ctx.request.body
    if(!(school_id&&school_menu_ids)){
        ctx.body = {
            code:1,
            data:null,
            msg:'请填写完整信息'
        }
        return
    }
    const res = await schoolInfo.update({
        school_menu_ids:school_menu_ids.join(',')
    },{
        where:{
            school_id
        }
    })
    ctx.body = {
        code:200,
        data:null,
        msg:'设置成功'
    }
}
// 获取可配置菜单
const getPageList = async (ctx,next)=>{
    const user_id = ctx.state.user_id
    let res = []
    if(user_id===1){
        res = getMenuPageList()
    }
    ctx.body = {
        code:200,
        data:res,
        msg:'获取成功'
    }
}
module.exports = {
    addSchool,
    getSchool,
    getPageList,
    setSchoolMenu,
    adduser,
    editTeacher,
    getUserList
}